<?php 
require_once("inc_security.php");
//check quyen them sua xoa
checkAddEdit("edit");
   $errorMsg = "";
	//Khai bao Bien
	$fs_redirect 							= base64_decode(getValue("url","str","GET",base64_encode("listing.php")));
	$record_id 								= getValue("record_id");
//Call Class generate_form();
	$myform 									= new generate_form();
	//Loai bo chuc nang thay the Tag Html
	
    $pro_cat_man_id = new db_query("SELECT pro_cat_id 
                                                FROM product
                                                WHERE pro_id =".$record_id);
    while ($row = mysql_fetch_assoc($pro_cat_man_id->result))
    {
        $pro_cat_id_current = $row['pro_cat_id'];
    }
    
    $categoriesArr = array();
    $categories = new db_query("SELECT * 
										 FROM categories
										 ORDER BY cat_id DESC
										 ");
    while($row	=	mysql_fetch_assoc($categories->result)){
        $categoriesArr[$row['cat_id']] = $row['cat_name'];
    }
	$myform->add("pro_name","pro_name",0,0,"",0,translate_text("Vui lòng nhập tên sản phẩm"),0,"");
	$myform->add("pro_cat_id","pro_cat_id",1,0,'',0,"",0,"");	
	$myform->add("pro_price", "pro_price", 3, 0,"",1, "Vui lòng nhập giá cho sản phẩm", 0, "");
    $myform->add("pro_information_summary","pro_information_summary",6,0,"",1,"Vui lòng điền thông số kĩ thuật của của sản phẩm");
    $myform->add("pro_information","pro_information",6,0,"",1,"Vui lòng điền nội dung  sản phẩm");
    //$myform->add("pro_image","pro_image", 0, 0, 0, 1,"Vui lòng thêm ảnh cho sản phẩm", 1,"Vui lòng thêm ảnh cho sản phẩm");
	//Add table
	 // Xử lý ảnh đại diện
		$pro_image = getValue("pro_image", "str", "POST", "");
		if($pro_image){
			$currentPath = $path.'Temp/'.$pro_image;
			$pro_title_image = time().$pro_image;
			$savePath = $path.$pro_title_image;
			rename($currentPath,$savePath);
			$myform->add("pro_image","pro_title_image",0,1,"",1,"Vui lòng chọn ảnh tiêu đề sản phẩm",0,"");
		}
	$myform->addTable($fs_table);
	//Warning Error!
	//Get Action.
	$action	= getValue("action", "str", "POST", "");
	if($action == "execute"){
      //  xóa ảnh sản phẩm
		$del_images = new db_execute('DELETE FROM image_products WHERE img_pro_id = '.$record_id);
		// Xử lý ảnh sản phẩm
		// add lại ảnh cũ :
        	$old_img_name = explode(',',getValue("old_img_name", "str", "POST", ""));
           if($old_img_name){
			
                foreach($old_img_name as $old_img){
					if($old_img){
						$add_img = new db_execute('INSERT INTO image_products(img_pro_id, img_name) VALUES('.$record_id.', "'.$old_img.'")');
					}
			   }
           }
         // add ảnh mới vào csdl
            $new_img_name =  explode(',',getValue("new_img_name", "str", "POST", ""));
            if($new_img_name){
                 foreach($new_img_name as $new_img){
                    if($new_img){
                        $currentPath = $path.'Temp/'.$new_img;
            			$new_name = time().$new_img;
            			$savePath = $path.'slide/'.$new_name;
            			if(rename($currentPath,$savePath)){
                            $add_img = new db_execute('INSERT INTO image_products(img_pro_id, img_name) VALUES('.$record_id.', "'.$new_name.'")');
                        }
                    }
                }
            }
         // Xóa ảnh cần xóa
          $del_img_name = explode(',',getValue("del_img_name", "str", "POST", ""));
          if($del_img_name){
              foreach($del_img_name as $del_img){
                @unlink($path.'slide/'.$del_img);
              }
          }
		if($errorMsg == ""){
		  $myform->removeHTML(0);
			$db_ex 	= new db_execute_return();
			$last_id = $db_ex->db_execute($myform->generate_update_SQL($id_field, $record_id));
			//echo $myform->generate_update_SQL($id_field, $record_id);
	
	
		//	$iParent = getValue("cat_parent_id","int","POST");
//			if($iParent > 0){
//				$db_ex = new db_execute("UPDATE categories_multi SET cat_has_child = 1 WHERE cat_id = " . $iParent);
//			}
			redirect("listing.php");
			exit();
		}
	}
	//add form for javacheck
	$myform->addFormname("edit");
	$myform->evaluate();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php echo $load_header?>
<?php  
$myform->checkjavascript();
$errorMsg .= $myform->strErrorField;

//lay du lieu cua record can sua doi
$db_data 	= new db_query("SELECT * FROM " . $fs_table . " WHERE " . $id_field . " = " . $record_id);
if($row 		= mysql_fetch_assoc($db_data->result)){
	foreach($row as $key=>$value){
		if($key!='lang_id' && $key!='admin_id') $$key = $value;
	}
}else{
		exit();
}
$images = new db_query('SELECT * FROM image_products WHERE img_pro_id = '.$pro_id);
   
?>
</head>
<body topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0">
<div class="overlay"></div>
<div class="wrappop">
    <div class="close">X</div>
    <table class="croptable">
        <tr>
            <td>
                Ảnh tải lên
            </td>
            <td>
                Ảnh hiển thị
            </td>
        </tr>
        <tr>
            <td>
                <button id="upload">Chọn ảnh</button>
                <span id="status" ></span>
				<input type="hidden" class="count" value="1" />
				<input type="hidden" class="path" value="<?php echo $path; ?>" />
				<input type="hidden" class="unloldtitle" value="" />
            </td>
			<td>
				
			</td>
        </tr>
        <tr>
            <td>
                    <div class="currentImg">
                    <div id="files" ></div>
                	<input type="hidden" id="currentLink" />   
                    <label>X1 <input type="text" size="4" id="x" name="x" /></label>
    				<label>Y1 <input type="text" size="4" id="y" name="y" /></label>
    				<label>X2 <input type="text" size="4" id="x2" name="x2" /></label>
    				<label>Y2 <input type="text" size="4" id="y2" name="y2" /></label>
    				<label>W <input type="text" size="4" id="w" name="w" /></label>
    				<label>H <input type="text" size="4" id="h" name="h" /></label>
                    <input type="button" class="crop btn" value ="Cắt ảnh" />
                </div>
            </td>
            <td>
                <div class="cropImg">
                <div class="newImg">
                </div>
				<input type="button" class="selectDetail"value="Chọn làm ảnh chi tiết" />
              Kích thước ảnh: 
					<input type="text" size="4" id="neww" name="w" readonly="true" /> x
					<input type="text" size="4" id="newh" name="h" readonly="true" /> px 
					<input type="hidden" class="newImgLink" />
					<button class="select_btn">Lưu ảnh</button>
					
                </div>
            </td>
        </tr>
		<tr>
			<td colspan="2">
				<div class="thumbImageGallery"></div>
				<button class="select_btn_detail">Lưu ảnh</button>
			</td>
		</tr>
    </table>
</div>
<?php  /*------------------------------------------------------------------------------------------------*/ ?>
<?php echo template_top(translate_text("Edit_city"))?>
<?php  /*------------------------------------------------------------------------------------------------*/ ?>
	<p align="center" style="padding-left:10px;">
	<?php 
	$form = new form();
	$form->create_form("add", $_SERVER["REQUEST_URI"], "post", "multipart/form-data",'onsubmit="validateForm(); return false;"');
	$form->create_table();
	?>
	
	<?php echo $form->text("Tên sản phẩm", "pro_name", "pro_name", $pro_name, "Tên sản phẩm", 1, 240, "", 255, "", "", "")?>
	<?php echo $form->select("Chọn loại sản phẩm", "pro_cat_id", "pro_cat_id", $categoriesArr,$pro_cat_id_current, "Loại sản phẩm")?>
	<?php echo $form->hidden("pro_image", "pro_image", "","", "", 1, 350, "", 255, "", "", "")?>
    <?php //echo $form->getFile("Chọn ảnh","pro_image","pro_image","ảnh sản phẩm",1,34);?>
	  <tr>
		<td  class="form_name">Ảnh đại diện: </td>
		<td  class="form_text"><a class="titleimage">Chọn ảnh</a>
		</td>
	</tr>
		<td>&nbsp;</td>
		<td>
			<div class="titleImg">
				<img src="<?php echo$path.$pro_image; ?>" />
				<input type="hidden" class="oldtitleImgLink" value="<?php echo$pro_image; ?>" />
			</div>                  
		</td> 
	</tr>
	<tr>
		<td  class="form_name">Ảnh sản phẩm: </td>
		<td  class="form_text"><a class="Detail">Chọn ảnh</a>
		</td>
	</tr>
		<td>&nbsp;</td>
		<td>
			<div class="detailImgs">
        <?php
			$old_img_name ='';
            while($image = mysql_fetch_assoc($images->result)):
			if($old_img_name){
				$old_img_name .= ','. $image['img_name'];
			}
			else{
				$old_img_name = $image['img_name'];
			}
        ?>
            <div class="detailimg">
                <img src="<?php echo$path.'slide/'.$image['img_name'];?>" />
                <input type="hidden" class="detailimglink" value="<?php echo$image['img_name']; ?>" />
            </div>
         <?php  
            endwhile;
        ?>
			</div>
		</td>
	</tr>
	 <?php echo $form->hidden("old_img_name", "old_img_name",$old_img_name,"", "", 1, 350, "", 255, "", "", "")?>
    <?php echo $form->hidden("del_img_name", "del_img_name","","", "", 1, 350, "", 255, "", "", "")?>
    <?php echo $form->hidden("new_img_name", "new_img_name","","", "", 1, 350, "", 255, "", "", "")?>
    <?php echo $form->text("Giá sản phẩm", "pro_price", "pro_price", $pro_price, "Giá sản phẩm", 1, 240, "", 255, "", "", "")?>
    <?php echo $form->textarea("Thông số kỹ thuật cơ bản","pro_information_summary","pro_information_summary",$pro_information_summary,"",1,400,60);?>
    <?php echo $form->textarea("Thông tin sản phẩm","pro_information","pro_information",$pro_information,"Thông tin sản phẩm",1,500,600);?>
    <?php echo $form->close_table()?>
    <?php echo $form->create_table("2")?>
	<?php echo $form->button("submit" . $form->ec . "reset", "submit" . $form->ec . "reset", "submit" . $form->ec . "reset", "Cập nhật" . $form->ec . "Làm lại", "Cập nhật" . $form->ec . "Làm lại", '' . $form->ec . '', "");?>
	<?php echo $form->hidden("action", "action", "execute", "");?>
	
	<?php 
	$form->close_table();
	$form->close_form();
	unset($form);
	?>
	</p>
	<script type="text/javascript" >
	 var path =$('.path').val();
	$(function(){
	<!--------------Upload image ---------------->
		var btnUpload=$('#upload');
		var status=$('#status');
		new AjaxUpload(btnUpload, {
			action: 'form_upload.php',
			name: 'uploadfile',
			onSubmit: function(file, ext){
				 if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){ 
                    // extension is not allowed 
					status.text('Only JPG, PNG or GIF files are allowed');
					return false;
				}
				status.text('Uploading...');
			},
			onComplete: function(file, response){
				//On completion clear the status
				status.text('');
				//Add uploaded file to list
				if(response==="error"){
                    $('#files').addClass('error');
				} else{
				   var count = $('.count').val();
				   count++;
				   $('.count').val(count);
				    $('#files').html('<img id="cropbox" src="'+path+'Temp/'+response+'?'+new Date().getTime()+'" />');
                    $('#currentLink').val(response);
                    
			    	$('#cropbox').Jcrop({
            			onChange: showCoords,
            			onSelect: showCoords
	               	});
                }
			}
		});
		
	});
</script>
	 <script>             
	 <!--------------Show popup detail ---------------->
		$('.Detail').click(function(){
			$('.wrappop').css('display','block');
			$('.overlay').css('display','block');
			$('.selectDetail').css('display','block');
			$('.thumbImageGallery').css('display','block');
			$('.select_btn').css('display','none');
			$('.select_btn_detail').css('display','block');
			$('.detailimglink').each(function(){
				var detailimglink = $(this).val();
				$('<div class="showGallery"></div>').appendTo('.thumbImageGallery').html(''
					+'<img src="'+path+'slide/'+detailimglink+'" />'
					+'<input type="text" class="olddetailLink" value="'+detailimglink+'" />'
					+'<button class="deletold">Xóa </button>');
				
				$('.deletold').click(function(){
					var del_img_name = $('#del_img_name').val() ;
				    var del_old_name = $(this).closest('div').find('.olddetailLink').val();
					if(del_img_name){
						del_img_name +=','+ del_old_name;
						$('#del_img_name').val(del_img_name);
					}
					else{
						del_img_name = del_old_name;
						$('#del_img_name').val(del_img_name);
					}
					$(this).closest('div').remove();
				});
			});
			$('.detailImgs').html('');
		});
		$('.close').click(function(){
			$('.wrappop').css('display','none');
			$('.overlay').css('display','none');
		});
		$('.selectDetail').click(function(){
			var newImgLink = $('.newImgLink').val();
			if(newImgLink=='') return;
			$('<div class="showGallery"></div>').appendTo('.thumbImageGallery').html(''
				+'<img src="'+path+'Temp/'+newImgLink+'" />'
				+'<input type="text" class="detailLink" value="'+newImgLink+'" />'
				+'<button class="delet">Xóa </button>');
				$('.newImg').html('');
				$('.newImgLink').val('');
				$('.delet').click(function(){
					$(this).closest('div').remove();
				});
		});
		$('.select_btn_detail').click(function(){
			var detailLinks ='';
			var olddetailLinks ='';
			$('.olddetailLink').each(function(){
				var olddetailLink = $(this).val();
				$('<div class="detailimg"></div>').appendTo('.detailImgs').html('<img src="'+path+'slide/'+olddetailLink+'" />');
				if(olddetailLinks){
					olddetailLinks +=',' + olddetailLink;
				}
				else{
					olddetailLinks = olddetailLink;
				}
			});
			$('.detailLink').each(function(){
				var detailLink = $(this).val();
				$('<div class="detailimg"></div>').appendTo('.detailImgs').html(''
					+'<img src="'+path+'Temp/'+detailLink+'" />');
				if(detailLinks){
					detailLinks +=',' + detailLink;
				}
				else{
					detailLinks = detailLink;
				}
			});
			$('#old_img_name').val(olddetailLinks);
			$('#new_img_name').val(detailLinks);
			$('.wrappop').css('display','none');
			$('.overlay').css('display','none');
			$('#files').html('');
			$('.newImg').html('');
			$('#x').val('');
			$('#y').val('');
			$('#x2').val('');
			$('#y2').val('');
			$('#w').val('');
			$('#h').val('');
			$('.newImgLink').val('');
			$('#neww').val('');
			$('#newh').val('');
		});
<!--------------Show popup title ---------------->

		$('.titleimage').click(function(){
			var oldtitleImgLink = $('.oldtitleImgLink').val();
			$('.wrappop').css('display','block');
			$('.overlay').css('display','block');
			$('.select_btn').css('display','block');
			$('.selectDetail').css('display','none');
			$('.thumbImageGallery').css('display','none');
			$('.select_btn_detail').css('display','none');	
			$('.unloldtitle').val(oldtitleImgLink);
		});

		$('.close').click(function(){
			$('.wrappop').css('display','none');
			$('.overlay').css('display','none');
		});
		$('.select_btn').click(function(){
			var titleLink = $('.newImgLink').val();
			if(titleLink=='')return;
			var unloldtitle =$('.unloldtitle').val();
			$.ajax({
				type:'POST',
				data:'unl='+unloldtitle,
				url:'unlink_img.php'
			});
			$('.wrappop').css('display','none');
			$('.overlay').css('display','none');
			$('.titleImg').html('<img src="'+path+'Temp/'+titleLink+'?'+ new Date().getTime()+'" />');
			$('#pro_image').val(titleLink);
			$('#files').html('');
			$('.newImg').html('');
			$('#x').val('');
			$('#y').val('');
			$('#x2').val('');
			$('#y2').val('');
			$('#w').val('');
			$('#h').val('');
			 $('.newImgLink').val('');
			$('#neww').val('');
			$('#newh').val('');
	   });
	</script>
    <script>
	 <!--------------Show crop box ---------------->
	function showCoords(c)
	{
		$('#x').val(c.x);
		$('#y').val(c.y);
		$('#x2').val(c.x2);
		$('#y2').val(c.y2);
		$('#w').val(c.w);
		$('#h').val(c.h);
	};
	$('.crop').click(function(){
		var x = $('#x').val();
		var x2 = $('#x2').val();
		var y = $('#y').val();
		var y2 = $('#y2').val();
		var ImgWidth = $('#w').val();
		var ImgHeight = $('#h').val();
		var count = $('.count').val();
		var currentLink = $('#currentLink').val();
		if(!ImgWidth || !ImgHeight || ImgWidth == 0 || ImgHeight == 0)
			return;
		
		$.ajax({	
			type:'POST' ,
			data:'x='+x+'&y='+y+'&ImgWidth='+ImgWidth+'&ImgHeight='+ImgHeight+'&currentLink='+currentLink+'&count='+count,
			url: 'resizeImage.php' ,
			success:function(html){
				count++;
				$('.count').val(count);
				$('.newImg').html('<img class="newThumb"src="'+path+'Temp/'+html+'?'+ new Date().getTime()+'" />');
				$('.newImgLink').val(html);
				$('#neww').val(ImgWidth);
				$('#newh').val(ImgHeight);
			}
		});
	});
</script>
<?php echo template_bottom() ?>
<?php  /*------------------------------------------------------------------------------------------------*/ ?>
</body>
</html>